package com.droid.mvvmlib.widget.base;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.LayoutRes;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

/**
 * @author zyc0617
 * @since 2019/8/21 23:08
 */
public abstract class BaseCustomerView<T extends ViewDataBinding, M>
        extends LinearLayout implements ICustomerView<M>, View.OnClickListener {

    protected T dataBinding;
    private M viewData;
    private ICustomeViewActionListener mListener;

    public BaseCustomerView(Context context) {
        super(context);
        init();
    }

    public BaseCustomerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BaseCustomerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public View getRootView() {
        return dataBinding.getRoot();
    }

    private void init() {

        LayoutInflater inflater = LayoutInflater.from(getContext());
        if (inflater != null) {
            dataBinding = DataBindingUtil.inflate(inflater, getLayoutId(), this, false);
            dataBinding.getRoot().setOnClickListener(v -> {
                if (mListener != null) {
                    mListener.onAction(ICustomeViewActionListener.ACTION_ROOT_VIEW_CLICKED, v, viewData);
                }
                onRootClick(v);
            });
            this.addView(dataBinding.getRoot());
        }
    }

    @Override
    public void setData(M data) {
        viewData = data;
        setDataToView(viewData);
        if (dataBinding != null) {
            dataBinding.executePendingBindings();
        }
        onUpdateData();

    }

    protected T getDataBinding() {
        return dataBinding;
    }

    protected M getViewData() {
        return viewData;
    }

    protected void onUpdateData() {

    }

    @Override
    public void setActionListener(ICustomeViewActionListener listener) {
        this.mListener = listener;
    }

    @Override
    public void setStyle(int resId) {

    }

    @Override
    public void onClick(View v) {

    }

    @LayoutRes
    protected abstract int getLayoutId();

    protected abstract void setDataToView(M data);

    protected abstract void onRootClick(View view);
}
